package com.xiaoyun.seleniumlinux.config.listener;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.xiaoyun.seleniumlinux.config.cache.CookieCache;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.events.WebDriverListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;


/**
 * @author xiaoyun461
 * @date 2023/5/11 16:03
 */
@Slf4j
@Component
public class TimeConsumingListener implements WebDriverListener {

    static ThreadLocal<Long> TTL = new TransmittableThreadLocal<>();

    @Resource
    private CookieCache cookieCache;


    @Override
    public void beforeGet(WebDriver driver, String url) {
        log.info("=============beforeGet==============");
        long beforeGetTime = System.currentTimeMillis();
        log.info("=============当前时间戳为::{} =================", beforeGetTime);
        Long oldBeforeGetTime = TTL.get();
        if (Objects.nonNull(oldBeforeGetTime)) {
            return;
        }
        TTL.set(beforeGetTime);

    }

    @Override
    public void beforeGetPageSource(WebDriver driver) {
        log.info("=============beforeGetPageSource==============");
        long beforeGetPageSourceTime = System.currentTimeMillis();
        log.info("=============当前时间戳为::{} =================", beforeGetPageSourceTime);
    }

    @Override
    public void afterGet(WebDriver driver, String url) {
        log.info("=============afterGet==============");
        long afterGetTime = System.currentTimeMillis();
        log.info("=============当前时间戳为::{} =================", afterGetTime);
    }


    @Override
    public void afterGetPageSource(WebDriver driver, String result) {
        log.info("=============afterGetPageSource==============");
        long afterGetPageSourceGetTime = System.currentTimeMillis();
        log.info("=============当前时间戳为::{} =================", afterGetPageSourceGetTime);
        Long beforeGetTime = TTL.get();
        if (Objects.isNull(beforeGetTime)) {
            return;
        }
        log.info("=============当前耗时::{}毫秒 =================", afterGetPageSourceGetTime - beforeGetTime);
        TTL.remove();


        //检测是否需要开启 cookie 缓存
        if (!CookieCache.COOKIE_CACHE_FLAG) {
            return;
        }
        //当获取到页面的时候 将Cookie 缓存到 CookieCache中
        String url = driver.getCurrentUrl();
        Set<Cookie> cookies = driver.manage().getCookies();
        cookieCache.setCookie(url, cookies);
        log.info("正在将url:{} 的 cookie 添加到缓存中,cookies:{}", url, cookies);
    }
}
